package com.ttg.web.service.Impl;


import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.ttg.common.entities.BasePage;
import com.ttg.common.entities.BaseResult;
import com.ttg.common.enums.ErrorCodeEnums;
import com.ttg.common.enums.GradeTypeEnum;
import com.ttg.common.enums.TagTypeEnum;
import com.ttg.common.exception.BaseException;
import com.ttg.common.utils.DateTimeUtil;
import com.ttg.model.dto.*;
import com.ttg.model.dto.open.MemberConfigBindTagListDto;
import com.ttg.model.pojo.Admin;
import com.ttg.model.pojo.TagInfo;
import com.ttg.model.pojo.VipGradeConfig;
import com.ttg.model.vo.MemberConfigBindTagListVo;
import com.ttg.model.vo.MemberConfigListVo;
import com.ttg.model.vo.MemberConfigTagsForBindVo;
import com.ttg.web.dao.TagInfoDao;
import com.ttg.web.dao.VipGradeConfigDao;
import com.ttg.web.service.AdminService;
import com.ttg.web.service.VipGradeConfigService;
import io.swagger.models.auth.In;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @author zhangHongYuan
 * @description
 * @date 2023/6/8 11:19
 */
@Service
@Slf4j
public class VipGradeConfigServiceImpl implements VipGradeConfigService {


    @Autowired
    private AdminService adminService;

    @Autowired
    private VipGradeConfigDao vipGradeConfigDao;

    @Autowired
    private TagInfoDao tagInfoDao;

    @Override
    public BaseResult getMemberConfigList(MemberConfigListDto dto) {
        if (Objects.isNull(dto)||Objects.isNull(dto.getGradeType())) {
            throw new BaseException(ErrorCodeEnums.PARAM_IS_NULL);
        }

        List<VipGradeConfig> memberConfigList = vipGradeConfigDao.getMemberConfigList(dto);
        List<MemberConfigListVo> list = new ArrayList<>();
        if (Objects.nonNull(memberConfigList)) {
            memberConfigList.forEach(m -> {
                MemberConfigListVo vo = new MemberConfigListVo();
                BeanUtils.copyProperties(m, vo);
                if (Objects.nonNull(m.getEditTime())){
                    vo.setEditTime(DateTimeUtil.formatYYYY_MM_DD_HH_MM_SS(m.getEditTime()));
                }
                Admin byId = adminService.getById(m.getEditAdminId());
                if (Objects.nonNull(byId)){
                    vo.setEditName(byId.getAdmUserName());
                }
                List<TagInfo> gradeTags = tagInfoDao.queryBindGradeTags(m.getId());
                List<MemberConfigBindTagListVo> tagList = new ArrayList<>();
                if (Objects.nonNull(gradeTags)) {
                    gradeTags.forEach(g -> {
                        MemberConfigBindTagListVo tag = new MemberConfigBindTagListVo();
                        BeanUtils.copyProperties(g, tag);
                        Admin tagAdmin = adminService.getById(g.getAddId());
                        if (Objects.nonNull(tagAdmin)){
                            tag.setAddName(tagAdmin.getAdmUserName());
                        }
                        tagList.add(tag);
                    });
                }
                vo.setTagList(tagList);
                list.add(vo);
            });

        }
        return BaseResult.success(list);
    }

    @Override
    public BaseResult queryBindGradeTags(MemberConfigBindTagListDto dto) {
        if(Objects.isNull(dto) || null == dto.getGradeId()){
            //参数为空
            throw new BaseException(ErrorCodeEnums.PARAM_IS_NULL);
        }
        List<TagInfo> gradeTags = tagInfoDao.queryBindGradeTags(dto.getGradeId());
        List<MemberConfigBindTagListVo> list = new ArrayList<>();
        if (Objects.nonNull(gradeTags)) {
            gradeTags.forEach(g -> {
                MemberConfigBindTagListVo vo = new MemberConfigBindTagListVo();
                BeanUtils.copyProperties(g, vo);
                Admin byId = adminService.getById(g.getAddId());
                if (Objects.nonNull(byId)){
                    vo.setAddName(byId.getAdmUserName());
                }
                list.add(vo);
            });
        }
        return BaseResult.success(list);
    }

    @Override
    public BaseResult queryTagsForBind(MemberConfigBindTagListDto dto) {
        if(Objects.isNull(dto) || null == dto.getGradeId()){
            //参数为空
            throw new BaseException(ErrorCodeEnums.PARAM_IS_NULL);
        }
        VipGradeConfig config = vipGradeConfigDao.getById(dto.getGradeId());
        if (Objects.isNull(config) || null == config.getGradeType()){
            throw new BaseException(ErrorCodeEnums.VIP_GRADE_IS_NOT_EXIST);
        }
        Integer tagType = TagTypeEnum.TYPE_PRIVATE.getValue();
        if (config.getGradeType().equals(GradeTypeEnum.TYPE_PUBLIC.getValue())){
            tagType = TagTypeEnum.TYPE_PUBLIC.getValue();
        }
        BasePage<MemberConfigBindTagListDto> parse = dto.parse();
        BasePage<MemberConfigTagsForBindVo> pageSetting = new BasePage<>(parse.getCurrent(),parse.getSize(),parse.getTotalPage(),parse.isSearchCount());
        BasePage<MemberConfigTagsForBindVo> voBasePage = tagInfoDao.queryTagsForBind(pageSetting,dto.getGradeId(),tagType);
        return BaseResult.success(voBasePage);
    }


    @Override
    public BaseResult addOrEditMemberGradeConfig(MemberConfigAddOrUpdateDto dto) {
        if (Objects.isNull(dto) || Objects.isNull(dto.getConfigAddDtoList()) || Objects.isNull(dto.getEditAdminId()) || Objects.isNull(dto.getGradeType())){
            //参数为空
            throw new BaseException(ErrorCodeEnums.PARAM_IS_NULL);
        }
        if (dto.getConfigAddDtoList().size() < 1){
            return BaseResult.defaultFail();
        }
        List<VipGradeConfig> configs = vipGradeConfigDao.getVipGradeByTypeForEdit(dto.getGradeType());
        if (Objects.isNull(configs) || CollectionUtils.isEmpty(configs)){
            //参数错误
            throw new BaseException(ErrorCodeEnums.PARAM_VALIDATION_FAIL);
        }
        Map<Integer,VipGradeConfig> configMap = configs.stream().collect(Collectors.toMap(VipGradeConfig::getId,config->config));
        Set<Integer> configkeys = configMap.keySet();
        List<MemberConfigAddDto> configAddDtoList = dto.getConfigAddDtoList();
        Map<Integer,MemberConfigAddDto> updateMap = configAddDtoList.stream().collect(Collectors.toMap(MemberConfigAddDto::getId,config->config));
        for (Integer key : configkeys){
            if(null == updateMap.get(key)){
                continue;
            }
            VipGradeConfig vipGradeConfig = configMap.get(key);
            MemberConfigAddDto updateConfig = updateMap.get(key);
            vipGradeConfig.setVipName(updateConfig.getVipName());
            if (vipGradeConfig.getVipGrade() % 1 == 0){
                //正式达标等级可以绑定标签
                //取消原绑定
                tagInfoDao.cancelBindGradeByGradeId(vipGradeConfig.getId());
                if (Objects.nonNull(updateConfig.getTagIds()) && CollectionUtils.isNotEmpty(updateConfig.getTagIds())){
                    tagInfoDao.bindGradeId(vipGradeConfig.getId(),updateConfig.getTagIds(),vipGradeConfig.getGradeType());
                }
            }
        }
        vipGradeConfigDao.updateBatchById(configs);
        vipGradeConfigDao.sumBindTags(configkeys);
        return BaseResult.success(true);
    }


//    @Override
//    public BaseResult addOrEditMemberGradeConfig(MemberConfigAddOrUpdateDto dto) {
//        List<VipGradeConfig> vipGradeConfigs = new ArrayList<>();
//        dto.getConfigAddDtoList().stream().forEach(vipGrade -> {
//            VipGradeConfig vipGradeConfig = new VipGradeConfig();
//            if (Objects.isNull(vipGrade)){
//                throw new BaseException(ErrorCodeEnums.PARAM_IS_NULL);
//            }
//            if (StringUtils.isBlank(vipGrade.getVipName())){
//                throw new BaseException(ErrorCodeEnums.VIP_GRADE_NAME_IS_NULL);
//            }
//            if (Objects.isNull(vipGrade.getGrowthStartRange())||Objects.isNull(vipGrade.getGrowthEndRange())||vipGrade.getGrowthStartRange()<0||vipGrade.getGrowthEndRange()<0){
//                throw new BaseException(ErrorCodeEnums.RULES_GROWTH_MAX_ERROR);
//            }
//            if (vipGrade.getGrowthEndRange()<vipGrade.getGrowthStartRange()&&vipGrade.getGrowthEndRange()!=0||vipGrade.getGrowthEndRange()==vipGrade.getGrowthStartRange()){
//                throw new BaseException(ErrorCodeEnums.RULES_CONDITIONS_IS_ERROR);
//            }
//            BeanUtils.copyProperties(vipGrade, vipGradeConfig);
//            if (Objects.nonNull(vipGrade.getId())){
//                VipGradeConfig byId = vipGradeConfigDao.getById(vipGrade.getId());
//                if (Objects.nonNull(byId)){
//                    if (!vipGradeConfig.getGrowthStartRange().equals(byId.getGrowthStartRange()) || !vipGradeConfig.getGrowthEndRange().equals(byId.getGrowthEndRange()) || !vipGradeConfig.getVipName().equals(byId.getVipName())){
//                        vipGradeConfig.setEditTime(LocalDateTime.now());
//                        vipGradeConfig.setEditAdminId(dto.getEditAdminId());
//                    }
//                }
//            }else {
//                vipGradeConfig.setEditTime(LocalDateTime.now());
//                vipGradeConfig.setEditAdminId(dto.getEditAdminId());
//            }
//            vipGradeConfig.setGradeType(dto.getGradeType());
//            vipGradeConfigs.add(vipGradeConfig);
//        });
//        boolean flag = vipGradeConfigDao.saveOrUpdateBatch(vipGradeConfigs);
//        if (flag) {
//            return BaseResult.success("Success");
//        }
//        return BaseResult.defaultFail();
//    }

    @Override
    public BaseResult editMemberGradeConfig(MemberConfigEditDto dto) {
        if (Objects.isNull(dto)) {
            throw new BaseException(ErrorCodeEnums.PARAM_IS_NULL);
        }
        if (StringUtils.isBlank(dto.getId())) {
            throw new BaseException(ErrorCodeEnums.VIP_GRADE_ID_IS_NULL);
        }
        if (StringUtils.isNotBlank(dto.getVipGrade())) {
            VipGradeConfig memberConfigByGrade = vipGradeConfigDao.getMemberConfigByGrade(dto.getVipGrade());
            if (Objects.nonNull(memberConfigByGrade) && !memberConfigByGrade.getId().equals(Integer.valueOf(dto.getId()))) {
                throw new BaseException(ErrorCodeEnums.VIP_GRADE_IS_EXIST);
            }
        }
        VipGradeConfig vipGradeConfig = new VipGradeConfig();
        vipGradeConfig.setId(Integer.valueOf(dto.getId()));
        vipGradeConfig.setVipGrade(Double.valueOf(dto.getVipGrade()));
        vipGradeConfig.setVipName(dto.getVipName());


        if (vipGradeConfigDao.updateById(vipGradeConfig)) {
            return BaseResult.success("Success");
        }
        return BaseResult.defaultFail();
    }

    @Override
    public BaseResult deleteMemberGradeConfig(MemberConfigDeleteDto2 dto) {
        if (Objects.isNull(dto)) {
            log.error("【MemberManagementServiceImpl getMemberConfigList】参数为空");
            throw new BaseException(ErrorCodeEnums.PARAM_IS_NULL);
        }
        if (CollectionUtils.isEmpty(dto.getIds())) {
            log.error("【MemberManagementServiceImpl getMemberConfigList】id参数为空");
            throw new BaseException(ErrorCodeEnums.VIP_GRADE_ID_IS_NULL);
        }
        boolean b = vipGradeConfigDao.removeByIds(dto.getIds());
        if (b) {
            return BaseResult.success("Success");
        }
        return BaseResult.defaultFail();
    }

    @Override
    public BaseResult selectMemberGradeConfig(MemberConfigDeleteDto dto) {
        if (Objects.isNull(dto)) {
            log.error("【MemberManagementServiceImpl selectMemberGradeConfig】参数为空");
            throw new BaseException(ErrorCodeEnums.PARAM_IS_NULL);
        }
        if (StringUtils.isBlank(dto.getId())) {
            log.error("【MemberManagementServiceImpl selectMemberGradeConfig】id参数为空");
            throw new BaseException(ErrorCodeEnums.VIP_GRADE_ID_IS_NULL);
        }
        VipGradeConfig byId = vipGradeConfigDao.getById(dto.getId());
        if (Objects.isNull(byId)) {
            throw new BaseException(ErrorCodeEnums.VIP_GRADE_IS_NOT_EXIST);
        }
        MemberConfigListVo vo = new MemberConfigListVo();
        BeanUtils.copyProperties(byId, vo);
//        vo.setId(String.valueOf(byId.getId()));
//        vo.setVipGrade(String.valueOf(byId.getVipGrade()));
//        vo.setSettingTime(String.valueOf(byId.getSettingDate()));
//        vo.setConditionStart(String.valueOf(byId.getRatingStart()));
//        vo.setConditionEnd(String.valueOf(byId.getRatingEnd()));

//        vo.setDateType(String.valueOf(byId.getDateType()));
        return BaseResult.success(vo);
    }

    @Override
    public BaseResult equity(VipEquityDto vipEquityDto) {
        if (ObjectUtils.isEmpty(vipEquityDto)) {
            log.error("【MemberManagementServiceImpl equity】参数为空");
            throw new BaseException(ErrorCodeEnums.PARAM_IS_NULL);
        }
        if (StringUtils.isBlank(vipEquityDto.getId())) {
            log.error("【MemberManagementServiceImpl equity】会员id参数为空");
            throw new BaseException(ErrorCodeEnums.VIP_GRADE_ID_IS_NULL);
        }
        VipGradeConfig vipGradeConfig = vipGradeConfigDao.getById(vipEquityDto.getId());
        if (ObjectUtils.isEmpty(vipGradeConfig)) {
            throw new BaseException(ErrorCodeEnums.VIP_GRADE_IS_NOT_EXIST);
        }
        vipGradeConfig.setEquityDescription(vipEquityDto.getEquityDescription());

        if (vipGradeConfigDao.updateById(vipGradeConfig)){
            return BaseResult.success("Success");
        }
        return BaseResult.defaultFail();
    }

    @Override
    public BaseResult getVipGradeNameList(HashMap map) {
        if (ObjectUtils.isEmpty(map)||ObjectUtils.isEmpty(map.get("gradeType"))) {
            throw new BaseException(ErrorCodeEnums.PARAM_IS_NULL);
        }

        List<VipGradeConfig> vipGradeConfigs = vipGradeConfigDao.getVipGradeNameList((Integer)map.get("gradeType"));
        List<MemberConfigListVo> voList = new ArrayList<>();
        if (CollectionUtils.isNotEmpty(vipGradeConfigs)){
            for (VipGradeConfig config : vipGradeConfigs){
                MemberConfigListVo vo = new MemberConfigListVo();
                vo.setVipGrade(config.getVipGrade());
                vo.setVipName(config.getVipName());
                voList.add(vo);
            }
        }
        return BaseResult.success(voList);
    }
}
